import { reactive, ref } from 'vue';
import { definePlugin } from '@/components/@comp/create-component';

function useStep(form, defaultStep = 0) {
  const formValue = reactive({});
  const step = ref(defaultStep);

  const handleStep = (index) => {
    if (index > step) {
      form.validateFields().then((values) => {
        Object.assign(formValue, values);
        step.value = index;
      });
    } else {
      Object.assign(formValue, form.getFieldsValue());
      step.value = index;
    }
    setTimeout(() => {
      form.setFieldsValue(formValue);
    }, 0);
  };

  return { step, setStep: handleStep, value: formValue };
}

const FormStep = definePlugin({
  name: 'FormStep',
  priority: 'LOW',
  required: ['FormGroup'],
  subComponent: { useStep },
});

export default FormStep;
